﻿using S7.Net;

namespace DongFangGuoKai.WCSPlatform.WebApi.Utils
{
    /// <summary>
    /// PLC心跳工具类
    /// </summary>
    public class PlcHeartbeatTool
    {
        private Timer heartbeatTimer; // 心跳定时器
        private readonly Plc plc; // PLC连接对象
        private readonly int heartbeatInterval; // 心跳间隔时间（单位：毫秒）
        private readonly PlcDBAddress plcDBAddress;
        private readonly ILogger<PlcHeartbeatTool> logger;
        private bool isStarted; // 是否已启动心跳

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="plc"></param>
        /// <param name="interval">心跳间隔时间</param>
        /// <param name="plcDBAddress">Plc数据库地址</param>
        /// <param name="logger"></param>
        public PlcHeartbeatTool(Plc plc, int interval,PlcDBAddress plcDBAddress, ILogger<PlcHeartbeatTool> logger)
        {
            this.plc = plc;
            this.heartbeatInterval = interval;
            this.plcDBAddress = plcDBAddress;
            this.logger = logger;
            this.isStarted = false;
        }

        /// <summary>
        /// 发送心跳信号
        /// </summary>
        /// <param name="state"></param>
        public async Task SendHeartbeatAsync(object state)
        {
            try
            {
                if (plc.IsConnected) // 判断PLC是否连接
                {
                    var heartVal = (bool)plc.Read(plcDBAddress.WcsHeartbeat);
                    var readVal = heartVal;
                    if (heartVal)
                        readVal = false;
                    else
                        readVal = true;
                    await Task.Run(() => plc.Write(plcDBAddress.WcsHeartbeat, readVal)); // 使用 Task.Run 在新线程中执行写入操作
                    //logger.LogInformation("wcs心跳:写入成功,val:"+readVal);
                }
                else
                {
                    logger.LogError("wcs心跳:plc连接已关闭");
                    await StopHeartbeatAsync();
                }
            }
            catch (Exception ex)
            {
                logger.LogError($"wcs心跳:"+ex.Message);
                await StopHeartbeatAsync();
                throw;
            }
        }

        /// <summary>
        /// 启动发送心跳信号
        /// </summary>
        public void StartHeartbeat()
        {
            try
            {
                if (!isStarted)
                {
                    heartbeatTimer = new Timer(async state =>
                    {
                        try
                        {
                            await SendHeartbeatAsync(state);
                        }
                        catch (Exception)
                        {

                            throw;
                        }
                      
                    }, null, heartbeatInterval, heartbeatInterval);
                    isStarted = true;
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 停止发送心跳信号
        /// </summary>
        public async Task StopHeartbeatAsync()
        {
            if (isStarted)
            {
                await Task.Run(() =>
                {
                    heartbeatTimer.Dispose();
                    isStarted = false;
                });
            }
        }
        /// <summary>
        /// 启动WCS
        /// </summary>
        /// <returns></returns>
        public void StartWcs()
        {
            try
            {
                plc.Open();
                if (plc.IsConnected == false) throw new Exception("WCS系统启动失败");
                StartHeartbeat();
                logger.LogInformation("WCS系统启动");
            }
            catch (Exception)
            {
                throw;
            }
        }
    }


}
